package vn.com.demand.lux.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.DateFormat;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.nebula.widgets.datechooser.DateChooserCombo;
import org.eclipse.nebula.widgets.formattedtext.DateFormatter;
import org.eclipse.nebula.widgets.formattedtext.FormattedText;
import org.eclipse.nebula.widgets.formattedtext.NumberFormatter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.part.ViewPart;

import vn.com.demand.lux.Activator;
import vn.com.demand.lux.criteria.UpdateWarrantyExpenseCriteria;
import vn.com.demand.lux.model.AccountReceivableDetailBean;
import vn.com.demand.lux.model.InterestSummaryBean;
import vn.com.demand.lux.preferences.PreferenceConstants;
import vn.com.demand.lux.view.contentprovider.AccountReceivableContentProvider;
import vn.com.demand.lux.view.contentprovider.InterestSummaryContentProvider;
import vn.com.demand.lux.view.labelprovider.InterestCaculationLabelProvider;
import vn.com.demand.lux.view.labelprovider.InterestSummaryLabelProvider;
import vn.com.demand.util.DpUtils;
import vn.com.demand.util.Validator;
import vn.com.demand.util.XMLUtils;
import vn.com.demand.widget.SearchableDialogActivator;
import vn.com.demand.widget.SelectItemCodeHeader;

import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

public class UpdateWarrantyExpense extends ViewPart {

	private Button importButton;
	private Button caculateButton;
	private Button excelButton;
	private Button xmlButton;
	private DateChooserCombo iiTodate;
	private DateChooserCombo iiDate;
	private TableViewer caculationTableViewer;
	private Table caculationTable;
	private TableViewer detailTableViewer;
	private Table detailTable;
	private Text iiCurrency;
	private Text iiExchangeRate;
	private SearchableDialogActivator liFinancialIncomeLedger;
	private SearchableDialogActivator liDefferedRevenueLedger;
	private SearchableDialogActivator liInstallmentLedger;
	private SearchableDialogActivator giResource;
	private SearchableDialogActivator giJournalCode;
	private Text giDivision;
	public static final String ID = "vn.com.demand.lux.view.UpdateWarrantyExpense"; //$NON-NLS-1$
	private UpdateWarrantyExpenseCriteria criteria;
	private List<InterestSummaryBean> interestSummatyList = new ArrayList<InterestSummaryBean>();
	private FormattedText iiEchangeRateFormatText;
	private ArrayList<AccountReceivableDetailBean> caculateResultList = new ArrayList<AccountReceivableDetailBean>();
	private InterestSummaryLabelProvider interestSummaryLabelProvider;
	private InterestCaculationLabelProvider interestCaculationLabelProvider;
	public static final int ROUND_SCALE = 2;
	public static final int VND_ROUND_SCALE = 2;
	public static final int ROUND_MODE = BigDecimal.ROUND_HALF_UP;
	/**
	 * Create contents of the view part
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		FormToolkit toolkit = new FormToolkit(Display.getCurrent());
		Composite container = toolkit.createComposite(parent, SWT.NONE);
		container.setLayout(new FillLayout());
		toolkit.paintBordersFor(container);

		final Form interestForwardingForm = toolkit.createForm(container);
		final Composite body = interestForwardingForm.getBody();
		body.setLayout(new FormLayout());
		toolkit.paintBordersFor(body);

		final Composite composite = toolkit.createComposite(body, SWT.NONE);
		final FillLayout fillLayout = new FillLayout();
		fillLayout.spacing = 5;
		composite.setLayout(fillLayout);
		final FormData fd_composite = new FormData();
		fd_composite.bottom = new FormAttachment(0, 130);
		fd_composite.left = new FormAttachment(0, 5);
		fd_composite.top = new FormAttachment(0, 5);
		composite.setLayoutData(fd_composite);
		toolkit.paintBordersFor(composite);

		final Section gSection = toolkit.createSection(composite, Section.COMPACT | Section.TITLE_BAR | Section.FOCUS_TITLE);
		gSection.setText("General Information");

		final Composite giComposite = toolkit.createComposite(gSection, SWT.NONE);
		giComposite.setLayout(new FormLayout());
		gSection.setClient(giComposite);
		toolkit.paintBordersFor(giComposite);

		final Label divisionLabel = toolkit.createLabel(giComposite, "Division", SWT.NONE);
		divisionLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		divisionLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));
		final FormData fd_divisionLabel = new FormData();
		fd_divisionLabel.right = new FormAttachment(0, 65);
		fd_divisionLabel.left = new FormAttachment(0, 20);
		fd_divisionLabel.top = new FormAttachment(0, 11);
		fd_divisionLabel.bottom = new FormAttachment(0, 24);
		divisionLabel.setLayoutData(fd_divisionLabel);

		giDivision = toolkit.createText(giComposite, null, SWT.NONE);
		giDivision.setText(PreferenceConstants.INTEREST_SUMMARY_DIVISION);
		final FormData fd_giDivision = new FormData();
		fd_giDivision.right = new FormAttachment(100, -22);
		fd_giDivision.left = new FormAttachment(0, 95);
		fd_giDivision.bottom = new FormAttachment(0, 30);
		fd_giDivision.top = new FormAttachment(0, 11);
		giDivision.setLayoutData(fd_giDivision);

//		giJournalCode = toolkit.createText(giComposite, null, SWT.NONE);
		SelectItemCodeHeader header = new SelectItemCodeHeader(null,
		"select * from DEMAND_JournalList");
		giJournalCode = new SearchableDialogActivator(giComposite, SWT.NONE, header);
		giJournalCode.setText(PreferenceConstants.INTEREST_SUMMARY_JOURNAL_CODE);
		final FormData fd_giJournalCode = new FormData();
		fd_giJournalCode.right = new FormAttachment(100, -22);
		fd_giJournalCode.left = new FormAttachment(0, 95);
		fd_giJournalCode.bottom = new FormAttachment(0, 61);
		fd_giJournalCode.top = new FormAttachment(0, 41);
		giJournalCode.setLayoutData(fd_giJournalCode);
		
		SelectItemCodeHeader resourceHeader = new SelectItemCodeHeader(null, "select res_id as code , fullname as description from DEMAND_ResourceList");
		giResource = new SearchableDialogActivator(giComposite, SWT.NONE, resourceHeader);
		final FormData fd_giResource = new FormData();
		fd_giResource.right = new FormAttachment(100, -22);
		fd_giResource.left = new FormAttachment(0, 95);
		fd_giResource.bottom = new FormAttachment(0, 91);
		fd_giResource.top = new FormAttachment(0, 71);
		giResource.setLayoutData(fd_giResource);

		final Label divisionLabel_1 = toolkit.createLabel(giComposite, "Journal code", SWT.NONE);
		final FormData fd_divisionLabel_1 = new FormData();
		fd_divisionLabel_1.right = new FormAttachment(0, 80);
		fd_divisionLabel_1.left = new FormAttachment(0, 20);
		fd_divisionLabel_1.bottom = new FormAttachment(0, 54);
		fd_divisionLabel_1.top = new FormAttachment(0, 41);
		divisionLabel_1.setLayoutData(fd_divisionLabel_1);
		divisionLabel_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		divisionLabel_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		final Label divisionLabel_2 = toolkit.createLabel(giComposite, "Resource", SWT.NONE);
		final FormData fd_divisionLabel_2 = new FormData();
		fd_divisionLabel_2.right = new FormAttachment(0, 80);
		fd_divisionLabel_2.left = new FormAttachment(0, 20);
		fd_divisionLabel_2.bottom = new FormAttachment(0, 84);
		fd_divisionLabel_2.top = new FormAttachment(0, 71);
		divisionLabel_2.setLayoutData(fd_divisionLabel_2);
		divisionLabel_2.setForeground(SWTResourceManager.getColor(0, 0, 255));
		divisionLabel_2.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		final Section ledgerInformationSection = toolkit.createSection(composite, Section.TITLE_BAR | Section.FOCUS_TITLE);
		ledgerInformationSection.setText("Ledger Information");

		final Composite liComposite = toolkit.createComposite(ledgerInformationSection, SWT.NONE);
		liComposite.setLayout(new FormLayout());
		ledgerInformationSection.setClient(liComposite);
		toolkit.paintBordersFor(liComposite);

		//liInstallmentLedger = toolkit.createText(liComposite, null, SWT.NONE);
		SelectItemCodeHeader installmentLedgerHeader = new SelectItemCodeHeader(null,
		"select * from DEMAND_LedgerList");
		liInstallmentLedger = new SearchableDialogActivator(liComposite, SWT.NONE, installmentLedgerHeader);
		liInstallmentLedger.setText(PreferenceConstants.INTEREST_SUMMARY_INSTALLMENT_LEDGER);
		final FormData fd_liInstallmentLedger = new FormData();
		fd_liInstallmentLedger.right = new FormAttachment(100, -5);
		fd_liInstallmentLedger.left = new FormAttachment(0, 135);
		fd_liInstallmentLedger.bottom = new FormAttachment(0, 31);
		fd_liInstallmentLedger.top = new FormAttachment(0, 11);
		liInstallmentLedger.setLayoutData(fd_liInstallmentLedger);

		final Label divisionLabel_3 = toolkit.createLabel(liComposite, "Installment ledger", SWT.NONE);
		final FormData fd_divisionLabel_3 = new FormData();
		fd_divisionLabel_3.right = new FormAttachment(0, 130);
		fd_divisionLabel_3.left = new FormAttachment(0, 5);
		fd_divisionLabel_3.bottom = new FormAttachment(0, 23);
		fd_divisionLabel_3.top = new FormAttachment(0, 10);
		divisionLabel_3.setLayoutData(fd_divisionLabel_3);
		divisionLabel_3.setForeground(SWTResourceManager.getColor(0, 0, 255));
		divisionLabel_3.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		final Label divisionLabel_1_1 = toolkit.createLabel(liComposite, "Deffered revenue ledger", SWT.NONE);
		final FormData fd_divisionLabel_1_1 = new FormData();
		fd_divisionLabel_1_1.right = new FormAttachment(0, 130);
		fd_divisionLabel_1_1.left = new FormAttachment(0, 5);
		fd_divisionLabel_1_1.bottom = new FormAttachment(0, 53);
		fd_divisionLabel_1_1.top = new FormAttachment(0, 40);
		divisionLabel_1_1.setLayoutData(fd_divisionLabel_1_1);
		divisionLabel_1_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		divisionLabel_1_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		SelectItemCodeHeader defferedRevenueHeader = new SelectItemCodeHeader(null, "select * from DEMAND_LedgerListDefferRevenue");
		liDefferedRevenueLedger = new SearchableDialogActivator(liComposite, SWT.NONE, defferedRevenueHeader);
		liDefferedRevenueLedger.setText(PreferenceConstants.INTEREST_SUMMARY_DEFERRED_REVENUE_LEDGER);
		final FormData fd_liDefferedRevenueLedger = new FormData();
		fd_liDefferedRevenueLedger.right = new FormAttachment(100, -5);
		fd_liDefferedRevenueLedger.left = new FormAttachment(0, 135);
		fd_liDefferedRevenueLedger.bottom = new FormAttachment(0, 61);
		fd_liDefferedRevenueLedger.top = new FormAttachment(0, 41);
		liDefferedRevenueLedger.setLayoutData(fd_liDefferedRevenueLedger);

		Label divisionLabel_2_1;
		divisionLabel_2_1 = toolkit.createLabel(liComposite, "Financial income ledger", SWT.NONE);
		final FormData fd_divisionLabel_2_1 = new FormData();
		fd_divisionLabel_2_1.left = new FormAttachment(0, 5);
		fd_divisionLabel_2_1.right = new FormAttachment(0, 115);
		fd_divisionLabel_2_1.bottom = new FormAttachment(0, 83);
		fd_divisionLabel_2_1.top = new FormAttachment(0, 70);
		divisionLabel_2_1.setLayoutData(fd_divisionLabel_2_1);
		divisionLabel_2_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		divisionLabel_2_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));
		
		SelectItemCodeHeader financialIncomeHeader = new SelectItemCodeHeader(null , "select * from DEMAND_LedgerListRevenue");
		try {
			liFinancialIncomeLedger = new SearchableDialogActivator(
					liComposite, SWT.NONE, financialIncomeHeader);
			liFinancialIncomeLedger
					.setText(PreferenceConstants.INTEREST_SUMMARY_FINANCIAL_INCOME_LEDGER);
			final FormData fd_liFinancialIncomeLedger = new FormData();
			fd_liFinancialIncomeLedger.right = new FormAttachment(100, -5);
			fd_liFinancialIncomeLedger.left = new FormAttachment(0, 135);
			fd_liFinancialIncomeLedger.bottom = new FormAttachment(0, 91);
			fd_liFinancialIncomeLedger.top = new FormAttachment(0, 71);
			liFinancialIncomeLedger.setLayoutData(fd_liFinancialIncomeLedger);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		Label divisionLabel_1_1_1;

		Label divisionLabel_2_1_1;

		Label divisionLabel_3_1_1;

		final Composite detailComposite = toolkit.createComposite(body, SWT.BORDER | SWT.EMBEDDED);
		final FillLayout fillLayout_1 = new FillLayout(SWT.VERTICAL);
		fillLayout_1.spacing = 10;
		detailComposite.setLayout(fillLayout_1);
		final FormData fd_detailComposite = new FormData();
		fd_detailComposite.bottom = new FormAttachment(100, -32);
		fd_detailComposite.top = new FormAttachment(0, 130);
		fd_detailComposite.left = new FormAttachment(0, 5);
		fd_detailComposite.right = new FormAttachment(100, -5);
		detailComposite.setLayoutData(fd_detailComposite);
		toolkit.paintBordersFor(detailComposite);

		final Section detailsSection = toolkit.createSection(detailComposite, Section.TITLE_BAR | Section.FOCUS_TITLE);
		detailsSection.setText("Details");

		final Composite detailCompo = toolkit.createComposite(detailsSection, SWT.NONE);
		detailCompo.setLayout(new FillLayout());
		detailsSection.setClient(detailCompo);
		toolkit.paintBordersFor(detailCompo);

		detailTableViewer = new TableViewer(detailCompo, SWT.FULL_SELECTION | SWT.BORDER);
		detailTable = detailTableViewer.getTable();
		toolkit.adapt(detailTable, true, true);
		detailTable.setLinesVisible(true);
		detailTable.setHeaderVisible(true);

		final TableColumn newColumnTableColumn = new TableColumn(detailTable, SWT.NONE);
		newColumnTableColumn.setWidth(100);
		newColumnTableColumn.setText("Contract number");

		final TableColumn newColumnTableColumn_9 = new TableColumn(detailTable, SWT.NONE);
		newColumnTableColumn_9.setWidth(100);
		newColumnTableColumn_9.setText("Customer code");

		final TableColumn newColumnTableColumn_8 = new TableColumn(detailTable, SWT.NONE);
		newColumnTableColumn_8.setWidth(100);
		newColumnTableColumn_8.setText("Customer name");

		final TableColumn newColumnTableColumn_7 = new TableColumn(detailTable, SWT.NONE);
		newColumnTableColumn_7.setWidth(100);
		newColumnTableColumn_7.setText("Cost center");

		final TableColumn newColumnTableColumn_6 = new TableColumn(detailTable, SWT.NONE);
		newColumnTableColumn_6.setWidth(100);
		newColumnTableColumn_6.setText("Total installment amount");

		final TableColumn newColumnTableColumn_5 = new TableColumn(detailTable, SWT.NONE);
		newColumnTableColumn_5.setWidth(100);
		newColumnTableColumn_5.setText("Total interest amount");

		final TableColumn newColumnTableColumn_4 = new TableColumn(detailTable, SWT.NONE);
		newColumnTableColumn_4.setWidth(100);
		newColumnTableColumn_4.setText("Accumulated collection amount");

		final TableColumn newColumnTableColumn_2 = new TableColumn(detailTable, SWT.NONE);
		newColumnTableColumn_2.setWidth(100);
		newColumnTableColumn_2.setText("Total forwarded interest amount");

		final TableColumn newColumnTableColumn_3 = new TableColumn(detailTable, SWT.NONE);
		newColumnTableColumn_3.setWidth(100);
		newColumnTableColumn_3.setText("Total interest amount to be forwarded");

		final TableColumn newColumnTableColumn_1 = new TableColumn(detailTable, SWT.NONE);
		newColumnTableColumn_1.setWidth(100);
		newColumnTableColumn_1.setText("Interest to be forwarded this month");
		
		interestSummaryLabelProvider = new InterestSummaryLabelProvider();
		interestSummaryLabelProvider.setList(interestSummatyList);
		detailTableViewer.setLabelProvider(interestSummaryLabelProvider);
		detailTableViewer.setContentProvider(new InterestSummaryContentProvider());
		
		final Section caculationResultSection = toolkit.createSection(detailComposite, Section.TITLE_BAR | Section.FOCUS_TITLE);
		caculationResultSection.setText("Caculation Result");

		final Composite caculationComposite = toolkit.createComposite(caculationResultSection, SWT.NONE);
		caculationComposite.setLayout(new FillLayout());
		caculationResultSection.setClient(caculationComposite);
		toolkit.paintBordersFor(caculationComposite);

		caculationTableViewer = new TableViewer(caculationComposite, SWT.FULL_SELECTION | SWT.BORDER);
		caculationTable = caculationTableViewer.getTable();
		toolkit.adapt(caculationTable, true, true);
		caculationTable.setLinesVisible(true);
		caculationTable.setHeaderVisible(true);

		final TableColumn newColumnTableColumn_28 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_28.setWidth(100);
		newColumnTableColumn_28.setText("Date");

		final TableColumn newColumnTableColumn_27 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_27.setWidth(100);
		newColumnTableColumn_27.setText("Division");

		final TableColumn newColumnTableColumn_26 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_26.setWidth(100);
		newColumnTableColumn_26.setText("Journal");

		final TableColumn newColumnTableColumn_25 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_25.setWidth(100);
		newColumnTableColumn_25.setText("Number");

		final TableColumn newColumnTableColumn_24 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_24.setWidth(100);
		newColumnTableColumn_24.setText("Type");

		final TableColumn newColumnTableColumn_23 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_23.setWidth(100);
		newColumnTableColumn_23.setText("SubType");

		final TableColumn newColumnTableColumn_22 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_22.setWidth(100);
		newColumnTableColumn_22.setText("Ledger");

		final TableColumn newColumnTableColumn_20 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_20.setWidth(100);
		newColumnTableColumn_20.setText("Description");

		final TableColumn newColumnTableColumn_21 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_21.setWidth(100);
		newColumnTableColumn_21.setText("Customer");

		final TableColumn newColumnTableColumn_19 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_19.setWidth(100);
		newColumnTableColumn_19.setText("Resource");

		final TableColumn newColumnTableColumn_18 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_18.setWidth(100);
		newColumnTableColumn_18.setText("YourReference");

		final TableColumn newColumnTableColumn_17 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_17.setWidth(100);
		newColumnTableColumn_17.setText("Currency");

		final TableColumn newColumnTableColumn_15 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_15.setWidth(100);
		newColumnTableColumn_15.setText("Exchange rate");

		final TableColumn newColumnTableColumn_16 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_16.setWidth(100);
		newColumnTableColumn_16.setText("DebitFC");

		final TableColumn newColumnTableColumn_14 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_14.setWidth(100);
		newColumnTableColumn_14.setText("CreditFC");

		final TableColumn newColumnTableColumn_13 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_13.setWidth(100);
		newColumnTableColumn_13.setText("DebitVND");

		final TableColumn newColumnTableColumn_11 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_11.setWidth(100);
		newColumnTableColumn_11.setText("CreditVND");

		final TableColumn newColumnTableColumn_12 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_12.setWidth(100);
		newColumnTableColumn_12.setText("Project code");

		final TableColumn newColumnTableColumn_10 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_10.setWidth(100);
		newColumnTableColumn_10.setText("Cost center");
		
		interestCaculationLabelProvider = new InterestCaculationLabelProvider();
		caculationTableViewer.setLabelProvider(interestCaculationLabelProvider);
		caculationTableViewer.setContentProvider(new AccountReceivableContentProvider());
		
		Composite buttonBar;
		buttonBar = toolkit.createComposite(body, SWT.NONE);
		buttonBar.setLayout(new FillLayout());
		final FormData fd_buttonBar = new FormData();
		fd_buttonBar.left = new FormAttachment(100, -639);
		fd_buttonBar.top = new FormAttachment(100, -30);
		fd_buttonBar.right = new FormAttachment(100, -5);
		fd_buttonBar.bottom = new FormAttachment(100, -5);
		buttonBar.setLayoutData(fd_buttonBar);
		toolkit.paintBordersFor(buttonBar);

		final Button button = toolkit.createButton(buttonBar, "&Refresh", SWT.NONE);
		button.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/reload.png"));
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doRefresh();
			}
		});
		button.setToolTipText("Refresh the result for detail section, depend on criteria");

		caculateButton = toolkit.createButton(buttonBar, "&Caculate", SWT.NONE);
		caculateButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/mp3player.png"));
		caculateButton.setEnabled(false);
		caculateButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doCaculate();
			}
		});
		caculateButton.setToolTipText("Caculate result from details");

		importButton = toolkit.createButton(buttonBar, "Import", SWT.NONE);
		importButton.setEnabled(false);
		importButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doImportToExact();
			}
		});
		importButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/fileimport.png"));

		excelButton = toolkit.createButton(buttonBar, "Export to Excel", SWT.NONE);
		excelButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/excel.gif"));
		excelButton.setEnabled(false);
		excelButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doExport2Excel();
			}
		});
		excelButton.setToolTipText("Export detail to excel");

		xmlButton = toolkit.createButton(buttonBar, "Export to XML", SWT.NONE);
		xmlButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/fileexport.png"));
		xmlButton.setEnabled(false);
		xmlButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doExport2XML();
			}
		});
		xmlButton.setToolTipText("Export caculation result to xml");

		final Button button_4 = toolkit.createButton(buttonBar, "Clos&e", SWT.NONE);
		button_4.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doClose();
			}
		});
		button_4.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/shutdown.png"));
		button_4.setToolTipText("Close this tab");

		Section installmentInformationSection;
		installmentInformationSection = toolkit.createSection(body, Section.TITLE_BAR | Section.FOCUS_TITLE);
		fd_composite.right = new FormAttachment(installmentInformationSection, -5, SWT.LEFT);
		final FormData fd_installmentInformationSection = new FormData();
		fd_installmentInformationSection.left = new FormAttachment(0, 605);
		fd_installmentInformationSection.right = new FormAttachment(detailComposite, 0, SWT.RIGHT);
		fd_installmentInformationSection.bottom = new FormAttachment(0, 130);
		fd_installmentInformationSection.top = new FormAttachment(0, 5);
		installmentInformationSection.setLayoutData(fd_installmentInformationSection);
		installmentInformationSection.setText("Installment Information");

		final Composite iComposite = toolkit.createComposite(installmentInformationSection, SWT.NONE);
		iComposite.setLayout(new FormLayout());
		installmentInformationSection.setClient(iComposite);
		toolkit.paintBordersFor(iComposite);

		iiExchangeRate = toolkit.createText(iComposite, null, SWT.NONE);
		final FormData fd_iiExchangeRate = new FormData();
		fd_iiExchangeRate.right = new FormAttachment(0, 375);
		fd_iiExchangeRate.bottom = new FormAttachment(0, 60);
		fd_iiExchangeRate.top = new FormAttachment(0, 41);
		fd_iiExchangeRate.left = new FormAttachment(0, 257);
		iiExchangeRate.setLayoutData(fd_iiExchangeRate);
		iiEchangeRateFormatText = new FormattedText(iiExchangeRate);
		NumberFormatter iiexchangeRateNumberFormatter = new NumberFormatter("###,###,###,###.00");
		iiEchangeRateFormatText.setFormatter(iiexchangeRateNumberFormatter);
		iiEchangeRateFormatText.setValue(16000);

//		iiDate = toolkit.createText(iComposite, null, SWT.NONE);

		iiCurrency = toolkit.createText(iComposite, null, SWT.NONE);
		iiCurrency.setText("USD");
		final FormData fd_iiCurrency = new FormData();
		fd_iiCurrency.left = new FormAttachment(0, 80);
		fd_iiCurrency.bottom = new FormAttachment(0, 60);
		fd_iiCurrency.top = new FormAttachment(0, 41);
		fd_iiCurrency.right = new FormAttachment(0, 168);
		iiCurrency.setLayoutData(fd_iiCurrency);
		divisionLabel_1_1_1 = toolkit.createLabel(iComposite, "Currency", SWT.NONE);
		final FormData fd_divisionLabel_1_1_1 = new FormData();
		fd_divisionLabel_1_1_1.top = new FormAttachment(0, 41);
		fd_divisionLabel_1_1_1.left = new FormAttachment(0, 5);
		fd_divisionLabel_1_1_1.right = new FormAttachment(0, 55);
		fd_divisionLabel_1_1_1.bottom = new FormAttachment(0, 54);
		divisionLabel_1_1_1.setLayoutData(fd_divisionLabel_1_1_1);
		divisionLabel_1_1_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		divisionLabel_1_1_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));
		divisionLabel_2_1_1 = toolkit.createLabel(iComposite, "Exchange rate", SWT.NONE);
		final FormData fd_divisionLabel_2_1_1 = new FormData();
		fd_divisionLabel_2_1_1.bottom = new FormAttachment(0, 54);
		fd_divisionLabel_2_1_1.top = new FormAttachment(0, 41);
		fd_divisionLabel_2_1_1.right = new FormAttachment(0, 245);
		fd_divisionLabel_2_1_1.left = new FormAttachment(0, 175);
		divisionLabel_2_1_1.setLayoutData(fd_divisionLabel_2_1_1);
		divisionLabel_2_1_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		divisionLabel_2_1_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		iiDate = new DateChooserCombo(iComposite, SWT.BORDER);
		final FormData fd_iiDate = new FormData();
		fd_iiDate.top = new FormAttachment(0, 11);
		fd_iiDate.left = new FormAttachment(0, 80);
		fd_iiDate.right = new FormAttachment(0, 168);
		fd_iiDate.bottom = new FormAttachment(0, 30);
		iiDate.setLayoutData(fd_iiDate);
		iiDate.setFormatter(new DateFormatter(Activator.getDefault().getDateFormatTypePreferences()));
		iiDate.setValue(new Date(System.currentTimeMillis()));
		toolkit.adapt(iiDate);

		iiTodate = new DateChooserCombo(iComposite, SWT.BORDER);
		final FormData fd_iiTodate = new FormData();
		fd_iiTodate.left = new FormAttachment(0, 257);
		fd_iiTodate.bottom = new FormAttachment(0, 30);
		fd_iiTodate.top = new FormAttachment(0, 11);
		fd_iiTodate.right = new FormAttachment(0, 375);
		iiTodate.setLayoutData(fd_iiTodate);
		iiTodate.setFormatter(new DateFormatter(Activator.getDefault().getDateFormatTypePreferences()));
		toolkit.adapt(iiTodate);
		divisionLabel_3_1_1 = toolkit.createLabel(iComposite, "To date", SWT.NONE);
		final FormData fd_divisionLabel_3_1_1 = new FormData();
		fd_divisionLabel_3_1_1.top = new FormAttachment(0, 11);
		fd_divisionLabel_3_1_1.right = new FormAttachment(0, 215);
		fd_divisionLabel_3_1_1.left = new FormAttachment(0, 175);
		fd_divisionLabel_3_1_1.bottom = new FormAttachment(0, 24);
		divisionLabel_3_1_1.setLayoutData(fd_divisionLabel_3_1_1);
		divisionLabel_3_1_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		divisionLabel_3_1_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		final Label divisionLabel_3_1_2 = toolkit.createLabel(iComposite, "Entry date", SWT.NONE);
		final FormData fd_divisionLabel_3_1_2 = new FormData();
		fd_divisionLabel_3_1_2.bottom = new FormAttachment(0, 24);
		fd_divisionLabel_3_1_2.top = new FormAttachment(0, 11);
		fd_divisionLabel_3_1_2.left = new FormAttachment(0, 5);
		fd_divisionLabel_3_1_2.right = new FormAttachment(0, 70);
		divisionLabel_3_1_2.setLayoutData(fd_divisionLabel_3_1_2);
		divisionLabel_3_1_2.setForeground(SWTResourceManager.getColor(0, 0, 255));
		divisionLabel_3_1_2.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));
		interestForwardingForm.setText("Interest Forwarding");
		//
		createActions();
		initializeToolBar();
		initializeMenu();
	}
	
	protected void doImportToExact() {
		String fileLocation = Activator.getDefault().getAccountReceivableXMLLocation() + "\\InterestForward.xml";
		String serverNameParam = "-r" + Activator.getDefault().getDatabaseProperties()[0];
		String dbNameParam = "-D" + Activator.getDefault().getDatabaseProperties()[2];
		String urlParam;
		File file = new File(fileLocation);
		if (null != file) {
			try {
				Document document = buildAccountReceivableDocument(caculateResultList);
				String tempFile = DpUtils
				.getTempFile("InterestSummaryXmlUnicodeRaw");
				XMLWriter writer = new org.dom4j.io.XMLWriter(
						new OutputStreamWriter(new FileOutputStream(tempFile)));
				writer.write(document);
				writer.flush();
				writer.close();
				try {
					//get correct mapping file
					String xslMapping = Activator.getDefault().getInterestForwardXSLMapping();
						XMLUtils.transform(tempFile, xslMapping, file);
				} catch (Exception e) {
					MessageDialog.openError(null, "Error", "You may not choose the correct xsl mapping file, please check");
					return;
				}
			} catch (Exception e) {
				e.printStackTrace();
				MessageDialog.openError(null, "Error", e.getMessage());
			}
		}	
		urlParam = "-URL" + file.getAbsolutePath();
		String[] exactCommand = new String[] {"C:\\Program Files\\Exact Software\\bin\\asimport.exe", serverNameParam, dbNameParam,
				"-u", "-~", "I", urlParam, "-TGLENTRIES", "-0Auto"};
		try {
			Runtime.getRuntime().exec(exactCommand);
		} catch (IOException e) {
			e.printStackTrace();
			MessageDialog.openError(null, "Error", e.getMessage());
		}
	}

	private void doClose() {
		getSite().getWorkbenchWindow().getActivePage().hideView(this);
	}
	
	private Document buildAccountReceivableDocument(
			List<AccountReceivableDetailBean> list) {
		String xmlDoubleFormat = new String("###############.00");
		double value = 0;
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("root");
		if (null != list && !list.isEmpty()) {
			for (AccountReceivableDetailBean d : list) {
				Element row = root.addElement("row");
				row.addElement("Division").addText(d.getDivision());
				row.addElement("Date").addText(DpUtils.format(d.getDate()));
				row.addElement("DocumentDate").addText(DpUtils.format(d.getDate()));
				row.addElement("Journal").addText(d.getJournal());
				row.addElement("Number").addText(String.valueOf(d.getNumber()));
				row.addElement("SubType").addText(d.getSubType());
				row.addElement("Type").addText(d.getType());
				row.addElement("Ledger").addText(d.getLedger());
				row.addElement("Description").addText(d.getDescription());
				row.addElement("CostCenter").addText(d.getCostCenter());
				row.addElement("Customer").addText(d.getCustomer());
				row.addElement("Resource").addText(d.getResource());
				row.addElement("ProjectCode").addText(d.getProjectCode());
				
				value =  DpUtils.round(d.getDebitVND(), ROUND_SCALE, ROUND_MODE);
				row.addElement("DebitVND").addText(value != 0 ? DpUtils.format(value, xmlDoubleFormat) : "0");
				
				value =  DpUtils.round(d.getCreditVND(), ROUND_SCALE, ROUND_MODE);
				row.addElement("CreditVND").addText(value != 0 ? DpUtils.format(value, xmlDoubleFormat) : "0");
				
				row.addElement("Currency").addText(d.getCurrency());
				
				value =  DpUtils.round(d.getDebitFC(), ROUND_SCALE, ROUND_MODE);
				row.addElement("DebitFC").addText(value != 0 ? DpUtils.format(value, xmlDoubleFormat) : "0");
				
				value =  DpUtils.round(d.getCreditFC(), ROUND_SCALE, ROUND_MODE);
				row.addElement("CreditFC").addText(value != 0 ? DpUtils.format(value, xmlDoubleFormat) : "0");
				
				value =  DpUtils.round(d.getExchangeRate(), ROUND_SCALE, ROUND_MODE);
				row.addElement("ExchangeRate").addText(DpUtils.format(value, xmlDoubleFormat));
				row.addElement("YourReference").addText(d.getYourReference());
			}
		}
		return document;
	}
	
	protected void doExport2XML() {
		if (null != caculateResultList && !caculateResultList.isEmpty()) {
			String fileLocation = getSavedFileLocation(new String[] {"XML File"}, new String[] {"*.xml"});
			File file = new File(fileLocation);
			if (null != file) {
				try {
					Document document = buildAccountReceivableDocument(caculateResultList);
					String tempFile = DpUtils
					.getTempFile("InterestSummaryXmlUnicodeRaw");
					XMLWriter writer = new org.dom4j.io.XMLWriter(
							new OutputStreamWriter(new FileOutputStream(tempFile)));
					writer.write(document);
					writer.flush();
					writer.close();
					try {
						//get correct mapping file
						String xslMapping = Activator.getDefault()
								.getInterestForwardXSLMapping();
						if (file.exists()) {
							if (MessageDialog
									.openQuestion(null, "Question",
											"The file is existed, Do you want to overwrite it?")) {
								XMLUtils.transform(tempFile, xslMapping, file);
							}
						} else {
							XMLUtils.transform(tempFile, xslMapping, file);
						}
					} catch (Exception e) {
						MessageDialog.openError(null, "Error", "You may not choose the correct xsl mapping file, please check");
						return;
					}
					MessageDialog.openInformation(null, "Exportation completed", "The account receivable has been exported to XML format, please find at "
							+ file.getAbsolutePath());
				} catch (Exception e) {
					e.printStackTrace();
					MessageDialog.openError(null, "Error", e.getMessage());
				}
			}
		} else {
			MessageDialog.openWarning(null, "Warning", "The caculation result is empty, you can not export to xml file");
		}
	}

	private String getSavedFileLocation(String[] fileFilterNames, String[] fileFilterTypes) {
		FileDialog fileDialog = new FileDialog(this.getViewSite().getShell(), SWT.SAVE);
		fileDialog.setFilterExtensions(fileFilterTypes);
		fileDialog.setFilterNames(fileFilterNames);
		String reportLocation = fileDialog.open();
		return reportLocation;
	}
	
	protected void doExport2Excel() {
		String reportLocation = getSavedFileLocation(new String[] {"Excel files"}, new String[] {"*.xls"});
		if (null != reportLocation) {
			File file = new File(reportLocation);
			if (file.exists()) {
				if (MessageDialog.openQuestion(null, "Question", "The file is exists, Do you want to overwrite it?")) {
					doWriteExcelFile(file);
				}
			} else {
				doWriteExcelFile(file);
			}
		}

	}

	private void doWriteExcelFile(File file) {
		WritableWorkbook workbook;
		try {
			workbook = Workbook.createWorkbook(file);
			WritableSheet sheet = workbook.createSheet("Interest", 0);
			int contentBeginRow = setExcelReportHeader(sheet, 0);
			setExcelReportContent(sheet, contentBeginRow);
			workbook.write();
			workbook.close();
			if (MessageDialog.openQuestion(null, "Completed", "Export completed, click OK to open the result file now or click Cancel to open it manually later")) {
				try {
					Runtime.getRuntime().exec("cmd.exe /C \"" + file.getAbsolutePath() + "\"");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (RowsExceededException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
	}
	
	private void setExcelReportContent(WritableSheet sheet, int row) {
		if (null != interestSummatyList && !interestSummatyList.isEmpty()) {
			try {
				WritableCellFormat numberFormat = new WritableCellFormat(NumberFormats.FLOAT);
				int col = 0;
				for (InterestSummaryBean interest : interestSummatyList) {
					sheet.addCell(new jxl.write.Label(col++, row, interest.getContractNumber()));
					sheet.addCell(new jxl.write.Label(col++, row, interest.getCustomerCode()));
					sheet.addCell(new jxl.write.Label(col++, row, interest.getCustomerName()));
					sheet.addCell(new jxl.write.Label(col++, row, interest.getCostCenter()));
					sheet.addCell(new jxl.write.Number(col++, row, interest.getInstallmentAmount(), numberFormat));
					sheet.addCell(new jxl.write.Number(col++, row, interest.getInterestAmount(), numberFormat));
					sheet.addCell(new jxl.write.Number(col++, row, interest.getCollectedAmount(), numberFormat));
					sheet.addCell(new jxl.write.Number(col++, row, interest.getForwardedAmount(), numberFormat));
					sheet.addCell(new jxl.write.Number(col++, row, interest.getInterestToForward(), numberFormat));
					sheet.addCell(new jxl.write.Number(col++, row++, interest.getInterestTobeForward(), numberFormat));
					col = 0;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private int setExcelReportHeader(WritableSheet resultSheet, int i) {
		WritableCellFormat tf;
		WritableCellFormat numberFormat = new WritableCellFormat(
				NumberFormats.FLOAT);
		try {
			WritableFont title = new WritableFont(WritableFont.ARIAL, 20,
					WritableFont.BOLD);
			title.setColour(Colour.BLACK);
			tf = new WritableCellFormat(title);
			tf.setAlignment(Alignment.LEFT);
			resultSheet.addCell(new jxl.write.Label(0, i++,
					"Interest Forwarding", tf));
			
			WritableFont criteriaFont = new WritableFont(WritableFont.ARIAL,
					10, WritableFont.BOLD);
			criteriaFont.setColour(Colour.BLUE);
			WritableCellFormat criteriaFormat = new WritableCellFormat(
					criteriaFont);
			// add an empty row
			i++;
			// Criteria
			WritableFont font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
			WritableCellFormat boldFormat = new WritableCellFormat(font);
			boldFormat.setAlignment(Alignment.LEFT);
			
			WritableFont alinRightFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD);
			WritableCellFormat alignRightCellFormat = new WritableCellFormat(alinRightFont);
			alignRightCellFormat.setAlignment(Alignment.RIGHT);
			
			resultSheet.addCell(new jxl.write.Label(0, i, "General Information", boldFormat));
			resultSheet.mergeCells(0, i, 1, i);
			resultSheet.addCell(new jxl.write.Label(2, i,
					"Installment Condition", boldFormat));
			resultSheet.mergeCells(2, i, 3, i);
			resultSheet.addCell(new jxl.write.Label(4, i, "Installment Information", boldFormat));
			resultSheet.mergeCells(4, i, 5, i);
			i++;
			
			DateFormat format = new DateFormat(Activator.getDefault()
					.getDateFormatTypePreferences());
			WritableCellFormat dateFormat = new WritableCellFormat(format);

			//1st header row
			resultSheet.addCell(new jxl.write.Label(0, i, "Division",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, i, giDivision.getText()));	
			resultSheet.addCell(new jxl.write.Label(2, i, "Installment Ledger",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(3, i, liInstallmentLedger.getText()));
			resultSheet.addCell(new jxl.write.Label(4, i, "Date",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.DateTime(5, i++, iiDate.getValue(), dateFormat));

			//2nd header row
			resultSheet.addCell(new jxl.write.Label(0, i, "Journal Code",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, i, DpUtils.trim(giJournalCode.getText())));
			resultSheet.addCell(new jxl.write.Label(2, i, "Deffered revenue ledger",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(3, i, DpUtils.trim(liDefferedRevenueLedger.getText())));
			resultSheet.addCell(new jxl.write.Label(4, i, "Currency",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(5, i++, iiCurrency.getText()));
			
			//3rd header row
			resultSheet.addCell(new jxl.write.Label(0, i, "Resource",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, i, giResource.getText()));
			resultSheet.addCell(new jxl.write.Label(2, i, "Financial income ledger",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(3, i, DpUtils.trim(liFinancialIncomeLedger.getText())));
			resultSheet.addCell(new jxl.write.Label(4, i, "Exchange rate",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(5, i++, DpUtils.format(((Number)iiEchangeRateFormatText.getValue()).doubleValue()), numberFormat));

			//Detail row header
			WritableFont underLineFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, true, UnderlineStyle.SINGLE);
			WritableCellFormat undeLineFontCellFormat = new WritableCellFormat(underLineFont);
			undeLineFontCellFormat.setAlignment(Alignment.LEFT);
			resultSheet.addCell(new jxl.write.Label(0, i++,
					"Detail Information", undeLineFontCellFormat));

			// set font and background color
			WritableFont header = new WritableFont(WritableFont.ARIAL, 10,
					WritableFont.BOLD);
			header.setColour(Colour.WHITE);
			WritableCellFormat hf = new WritableCellFormat(header);
			hf.setBackground(Colour.BLUE);
			hf.setAlignment(Alignment.CENTRE);
			hf.setVerticalAlignment(VerticalAlignment.CENTRE);
			hf.setWrap(true);
			int col = 0;
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Contract Number", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Customer Code", hf));
			resultSheet.setColumnView(col, 25);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Customer Name", hf));
			resultSheet.setColumnView(col, 10);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Cost Center", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Total Installment Amount", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Total Interest Amount", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Accumulated Collection Amount", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Total Forwarded Interst Amount", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet
					.addCell(new jxl.write.Label(col++, i, "Total Interest Amount to be forwarded", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i++, "Interest to be forwarded this month", hf));
			resultSheet.setColumnView(col, 20);
			return i;
		} catch (WriteException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	protected void doCaculate() {
		if (null != interestSummatyList && !interestSummatyList.isEmpty()) {
			//each interest will generate 2 result rows
			int row = 1;
			caculateResultList.clear();
			for (InterestSummaryBean interest : interestSummatyList) {
				//caculate for details which have interestTobeForward > 0
				if (interest.getInterestTobeForward() > 0) {
					//odd row
					AccountReceivableDetailBean oddDetail = new AccountReceivableDetailBean();
					oddDetail.setDate(iiDate.getValue());
					oddDetail.setDivision(giDivision.getText());
					oddDetail.setJournal(giJournalCode.getText());
					oddDetail.setNumber(row++);
					oddDetail.setType("N");
					oddDetail.setSubType("N");
					oddDetail.setLedger(liDefferedRevenueLedger.getText());
					oddDetail.setDescription("Interest forwarded of contract "
							+ DpUtils.trim(interest.getContractNumber()));
					oddDetail.setCustomer(DpUtils.trim(interest
							.getCustomerCode()));
					oddDetail.setResource(giResource.getText());
					oddDetail.setYourReference("INTEREST_FORWARDED");
					oddDetail.setCurrency(iiCurrency.getText());
					oddDetail.setExchangeRate(((Number) iiEchangeRateFormatText
							.getValue()).doubleValue());
					oddDetail
							.setDebitFC(DpUtils.round(interest
									.getInterestTobeForward(), ROUND_SCALE,
									ROUND_MODE));
					oddDetail.setDebitVND(DpUtils.round(oddDetail.getDebitFC()* oddDetail.getExchangeRate(), VND_ROUND_SCALE, ROUND_MODE));
					oddDetail.setProjectCode(DpUtils.trim(interest
							.getContractNumber()));
					oddDetail.setCostCenter(DpUtils.trim(interest
							.getCostCenter()));
					caculateResultList.add(oddDetail);
					
					//event row
					AccountReceivableDetailBean eventDetail = new AccountReceivableDetailBean();
					eventDetail.setDate(iiDate.getValue());
					eventDetail.setDivision(giDivision.getText());
					eventDetail.setJournal(giJournalCode.getText());
					eventDetail.setNumber(row++);
					eventDetail.setType("N");
					eventDetail.setSubType("N");
					eventDetail.setLedger(liFinancialIncomeLedger.getText());
					eventDetail
							.setDescription("Interest forwarded of contract "
									+ DpUtils
											.trim(interest.getContractNumber()));
					eventDetail.setCustomer(DpUtils.trim(interest
							.getCustomerCode()));
					eventDetail.setResource(giResource.getText());
					eventDetail.setYourReference("INTEREST_FORWARDED");
					eventDetail.setCurrency(iiCurrency.getText());
					eventDetail
							.setExchangeRate(((Number) iiEchangeRateFormatText
									.getValue()).doubleValue());
					eventDetail
							.setCreditFC(DpUtils.round(interest
									.getInterestTobeForward(), ROUND_SCALE,
									ROUND_MODE));
					eventDetail.setCreditVND(DpUtils.round(eventDetail.getCreditFC()* eventDetail.getExchangeRate(), VND_ROUND_SCALE, ROUND_MODE));
					eventDetail.setProjectCode(DpUtils.trim(interest
							.getContractNumber()));
					eventDetail.setCostCenter(DpUtils.trim(interest
							.getCostCenter()));
					caculateResultList.add(eventDetail);
				}
			}
			interestCaculationLabelProvider.setList(caculateResultList);
			caculationTableViewer.setInput(caculateResultList);
			importButton.setEnabled(!caculateResultList.isEmpty());
			xmlButton.setEnabled(!caculateResultList.isEmpty());
		}
	}

	protected void doRefresh() {
		if (doValidate()) {
			criteria = new UpdateWarrantyExpenseCriteria();
			criteria.setInstallmentLedger(DpUtils.trim(liInstallmentLedger.getText()));
			criteria.setDefferedRevenueLedger(DpUtils.trim(liDefferedRevenueLedger.getText()));
			criteria.setToDate(DpUtils.getSqlDate(iiTodate.getValue()));
			interestSummatyList = criteria.search();
			interestSummaryLabelProvider.setList(interestSummatyList);
			detailTableViewer.setInput(interestSummatyList);
			caculateButton.setEnabled(!interestSummatyList.isEmpty());
			excelButton.setEnabled(!interestSummatyList.isEmpty());
			//clear caculation result table 
			caculateResultList.clear();
			caculationTableViewer.setInput(caculateResultList);
			xmlButton.setEnabled(!caculateResultList.isEmpty());
		}
	}

	private boolean doValidate() {
		Color orange = new Color(null, 255, 200, 100);
		Color white = new Color(null, 255, 255, 255);
		if (!Validator.isValidJournalCode(giJournalCode.getText().trim())) {
			MessageDialog.openError(null, "Error", "Journal code is not valid");
			giJournalCode.setBackground(orange);
			giJournalCode.setFocus();
			return false;
		} else {
			giJournalCode.setBackground(white);
		}
		if (!Validator.isValidAccountNumber(liDefferedRevenueLedger.getText().trim())) {
			MessageDialog.openError(null, "Error", "Deffered Revenue Ledger is not valid");
			liDefferedRevenueLedger.setBackground(orange);
			liDefferedRevenueLedger.setFocus();
			return false;
		} else {
			liDefferedRevenueLedger.setBackground(white);
		}
		if (!Validator.isValidAccountNumber(liFinancialIncomeLedger.getText().trim())) {
			MessageDialog.openError(null, "Error", "Financial Income Ledger is not valid");
			liFinancialIncomeLedger.setBackground(orange);
			liFinancialIncomeLedger.setFocus();
			return false;
		} else {
			liFinancialIncomeLedger.setBackground(white);
		}
		if (!Validator.isValidAccountNumber(liInstallmentLedger.getText().trim())) {
			MessageDialog.openError(null, "Error", "Installment Ledger is not valid");
			liInstallmentLedger.setBackground(orange);
			liInstallmentLedger.setFocus();
			return false;
		} else {
			liInstallmentLedger.setBackground(white);
		}
		if (null == iiTodate.getValue()) {
			MessageDialog.openError(null, "Error", "Todate cannot be empty");
			iiTodate.setBackground(orange);
			iiTodate.setFocus();
			return false;
		} else {
			iiTodate.setBackground(white);
		}
		return true;
	}

	/**
	 * Create the actions
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar
	 */
	private void initializeToolBar() {
		IToolBarManager tbm = getViewSite().getActionBars().getToolBarManager();
	}

	/**
	 * Initialize the menu
	 */
	private void initializeMenu() {
		IMenuManager manager = getViewSite().getActionBars().getMenuManager();
	}

	@Override
	public void setFocus() {
		// Set the focus
	}

}
